package com.example.threaddemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产消费的 队列应用
 * true 则开始生产、消费
 * false 则停止生产
 */
class MyResource {
    private volatile boolean flag = true;//默认开启
    private AtomicInteger atomicInteger = new AtomicInteger();

    //传接口，而不是具体的类
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        //具体写，用于日志查询
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myPro() throws Exception {
        String data = null;
        boolean retValue;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t  插入队列" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t  插入队列" + data + "失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t 大老板叫停了，表示 flag = false，生产动作结束");
    }

    public void myCon() throws Exception {
        String result = null;
        while (flag) {
            result = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (null == result || result.equalsIgnoreCase("")) {
                //获取不到元素，叫停
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t 超过2s没有取到蛋糕，消费退出");
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t  消费队列蛋糕" + result + "成功");
        }
    }

    //老板叫停生产
    public void stop() throws Exception {
        this.flag = false;
    }

}

public class ProConsumerBlockQueueDemo {
    public static void main(String[] args) throws Exception {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 生产线程启动");
            try {
                myResource.myPro();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Prod").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 消费线程启动");
            try {
                myResource.myCon();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Con").start();

        TimeUnit.SECONDS.sleep(5);
        System.out.println("5s 后老板叫停");
        myResource.stop();
    }
}
